package com.aplink.generic.cloudmessage;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.aplink.generic.GenericActivity;
import com.aplink.generic.controller.GenericApplication;
import com.aplink.generic.pojo.CloudNotification;
import com.aplink.generic.pojo.MasterConfig;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;

    NotificationCompat.Builder builder;

    CloudNotification cloudNotification = null;

    private NotificationManager mNotificationManager;

    public GCMIntentService() {
        super("GCMIntentService");
        final MasterConfig masterConfig = GenericApplication.getInstance()
                .getMasterConfig();
        this.cloudNotification = masterConfig.getCloudNotification();
    }

    @Override
    protected void onHandleIntent(final Intent intent) {
        final Bundle extras = intent.getExtras();
        final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        final String messageType = gcm.getMessageType(intent);
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            sendNotification(extras.getString(this.cloudNotification
                    .getMessageTag()));
        }
    }

    private void sendNotification(final String msg) {
        this.mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, GenericActivity.class), 0);
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this)
                .setAutoCancel(true)
                .setContentTitle(this.cloudNotification.getContentTitle())
                .setSmallIcon(this.cloudNotification.getIconID())
                .setDefaults(
                        Notification.DEFAULT_LIGHTS
                                | Notification.DEFAULT_SOUND)
                .setContentText(msg);
        mBuilder.setContentIntent(contentIntent);
        this.mNotificationManager.notify(msg.hashCode(), mBuilder.build());
    }
}
